package com.mright.step01.compile;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.CtNewMethod;

import java.lang.reflect.Method;

/**
 * @author zhaochuanzhen
 * @since 2022/2/13 9:21 下午
 */
public class JavassistDemo {

    public static void main(String[] args) throws Exception {
        final ClassPool classPool = ClassPool.getDefault();
        final CtClass ctClass = classPool.makeClass("Hello world");
        final CtMethod ctMethod = CtNewMethod.make("public static void test() {\n" +
                "        System.out.println(\"你好，世界！\");\n" +
                "    }", ctClass);
        ctClass.addMethod(ctMethod);
        final Class aClass = ctClass.toClass();
        final Object obj = aClass.newInstance();
        final Method method = aClass.getDeclaredMethod("test");
        method.invoke(obj);
    }

}
